package statsyslogic

import (
	"context"
	"fmt"
	"go.uber.org/zap"
	"navi-mumbai/common/key/dbkey"
	"navi-mumbai/common/utils"
	"navi-mumbai/common/xerr"
	"strconv"
	"time"

	"navi-mumbai/app/rpc/stat/internal/svc"
	"navi-mumbai/app/rpc/stat/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type AddUserLoginLogLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewAddUserLoginLogLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddUserLoginLogLogic {
	return &AddUserLoginLogLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 记录用户登陆日志
func (l *AddUserLoginLogLogic) AddUserLoginLog(in *pb.AddUserLoginLogReq) (*pb.AddUserLoginLogResp, error) {
	defer utils.RecoverPanic()

	dt := time.Now().Format(dbkey.DateFormat2)
	dtt, err := strconv.ParseInt(dt, 10, 64)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}

	var id int64
	id, err = strconv.ParseInt(fmt.Sprintf("%d%s", in.Uid, dt), 10, 64)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, xerr.NewGrpcErrCodeMsg(xerr.RequestParamError, err.Error())
	}

	_, err = l.svcCtx.UserLoginLogModel.InsertOrUpdate(l.ctx, id, dtt, in.Uid, in.UserChannel)
	if err != nil {
		l.Logger.Errorf("err == ", zap.Error(err))
		return nil, err
	}

	return &pb.AddUserLoginLogResp{}, nil
}
